package com.zhj.common.web.apiversion;

import com.zhj.common.web.apiversion.annotation.ApiVersion;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * 自定义接口多版本映射器
 * @author zhj
 */
public class ApiVersionHandlerMapping extends RequestMappingHandlerMapping {

    /**
     * 所有的Controller对象会依次调用该方法，根据当前的Controller
     * @param handlerType
     * @return RequestCondition<?> 请求条件
     */
    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
        return new ApiVersionRequestCondition(apiVersion != null ? apiVersion.value() : 1.0);
    }

    /**
     * 所有的Controller对象会依次调用该方法，根据当前的Method信息
     * @param method
     * @return RequestCondition<?> 请求条件
     */
    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
        if (apiVersion == null) {
            // 方法没有尝试从类上找
            apiVersion = AnnotationUtils.findAnnotation(method.getDeclaringClass(), ApiVersion.class);
        }
        return new ApiVersionRequestCondition(apiVersion != null ? apiVersion.value() : 1.0);
    }
}
